package com.funkyfurrymonkey.load;
import openfl.events.Event;
import openfl.events.IOErrorEvent;
import openfl.net.URLRequest;
import openfl.net.URLLoader;

/**
 * ...
 * @author Marcos Martinez
 */
class XMLLoader
{
	private var m_cLoader:URLLoader;
	private var m_szXmlFile:String;
	public var m_xmlBody:Xml;
	
	// Constructor
	// szXmlFile is the file to be loaded.
	public function new( szXmlFile:String) 
	{
		
		m_szXmlFile = szXmlFile;
		}
	
	public function destroy()
	{
		if ( m_cLoader != null )
		{
			try {
				m_cLoader.removeEventListener(Event.COMPLETE, onComplete  );
				m_cLoader.removeEventListener(IOErrorEvent.IO_ERROR, onIOError);
			}
			catch (unknown : Dynamic)
			{
				trace(unknown);
			}
			
			m_cLoader = null;
		}
		
		doOnComplete = null;
		m_xmlBody = null;
	}
	
	public function startLoad():Void
	{
		var cRequest:URLRequest = new URLRequest(m_szXmlFile);
		m_cLoader = new URLLoader(cRequest);

		m_cLoader.addEventListener(Event.COMPLETE, onComplete  );
		m_cLoader.addEventListener(IOErrorEvent.IO_ERROR, onIOError);
	}
	
	// Called when the file has loaded.
	private function onComplete( e:Event)
	{ 
		m_xmlBody = Xml.parse(e.target.data);
		m_cLoader.removeEventListener(Event.COMPLETE, onComplete  );
		m_cLoader.removeEventListener(IOErrorEvent.IO_ERROR, onIOError);
		
		if ( onComplete != null )
			doOnComplete(m_xmlBody);
			
		}
		
	// Called if there is an error.
	private function onIOError(e:Event)
	{
		 trace ("onIOError : " + m_szXmlFile);
		 trace ( e.toString() );
		 trace ( e );
	}
	
	// Dymanic Functions
	
	public dynamic function doOnComplete(xml:Xml) { }
}